package com.example.boot2mybatis.close;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * 思路是这样具体实现需要自己研究，学习
 */
@RestController
public class ShutdownController implements ApplicationContextAware {

	private ApplicationContext context;
/*	@Autowired
	private DataService dataService;    
	@Autowired    
	private RequestHandler requestHandler;    
	@Autowired    
	private DependencyNotifier dependencyNotifier;    */


	//@EventListener
	public void onApplicationEvent(ContextClosedEvent event) {
	/*	// 备份数据
		dataService.backupData();
		// 停止接收新的请求
		requestHandler.stopAcceptingRequests();
		  // 处理未完成的请求
		requestHandler.waitForRequestsToComplete();
		  // 通知其他依赖组件
		 dependencyNotifier.notifyDependencies();
		 // 等待所有要素安全退出后，关闭系统
		 context.close();

	 */
	}

	/**
	 * 调用接口直接关闭应用
	 * @param applicationContext
	 * @throws BeansException
	 */
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		context = applicationContext;
	}

	@GetMapping("/shutDownContext")
	public String shutDownContext() {
		ConfigurableApplicationContext ctx = (ConfigurableApplicationContext) context;
		System.out.println("是否到这里...");
		ctx.close();
		return "context is shutdown";
	}
	@GetMapping("/")
	public String getIndex() {
		return "OK";
	}

}